﻿using System;
using System.Linq;
using MySql.Data.MySqlClient;
using System.Data;
using iRealtor.Maps.DataAccess.Models;

namespace iRealtor.Maps.DataAccess.Dao.EntityDataProviders
{
	public class GroupsDataProvider : EntityDataProvider<Group>
	{
		private const string INSERT_COMMAND = "INSERT INTO Groups(Longitude, Latitude) VALUES(@Longitude, @Latitude); SELECT @@IDENTITY;";
		private const string UPDATE_COMMAND = "UPDATE Groups SET Longitude=@Longitude, Latitude=@Latitude WHERE GroupId=@GroupId;";
		private const string SELECT_COMMAND = "SELECT * FROM Groups WHERE GroupId=@GroupId;";

		public override void Save(Group entity, IMySqlCommandCreater cmdCreater)
		{
			MySqlCommand cmd = cmdCreater.CreateCommand();

			if (entity.GroupId == 0)
			{
				cmd.CommandText = INSERT_COMMAND;
			}
			else
			{
				cmd.CommandText = UPDATE_COMMAND;
				cmd.Parameters.Add("@GroupId", MySqlDbType.Int32).Value = entity.GroupId;
			}

			cmd.Parameters.Add("@Longitude", MySqlDbType.Float).Value = entity.Longitude;
			cmd.Parameters.Add("@Latitude", MySqlDbType.Float).Value = entity.Latitude;

			if (entity.GroupId == 0)
			{
				entity.GroupId = Convert.ToInt32(cmd.ExecuteScalar());
			}
			else
			{
				if (cmd.ExecuteNonQuery() == 0)
				{
					throw new Exception(string.Format("Group({0}) was not found in database.", entity.GroupId));
				}
			}
		}

		public override Group Load(object key, IMySqlCommandCreater cmdCreater)
		{
			MySqlCommand cmd = cmdCreater.CreateCommand(SELECT_COMMAND);
			cmd.Parameters.Add("@GroupId", MySqlDbType.Int32).Value = key;

			return Load(cmd).FirstOrDefault();
		}

		public override Group Load(DataRow row)
		{
			var group = new Group();

			if (!(row["GroupId"] is DBNull))
				group.GroupId = Convert.ToInt32(row["GroupId"]);
			if (!(row["Longitude"] is DBNull))
				group.Longitude = Convert.ToDouble(row["Longitude"]);
			if (!(row["Latitude"] is DBNull))
				group.Latitude = Convert.ToDouble(row["Latitude"]);

			return group;
		}
	}
}
